import { login } from '@/services/admin';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, Helmet } from '@umijs/max';
import { message } from 'antd';
import Settings from '../../../config/defaultSettings';
import React from 'react';
import { md5 } from 'js-md5';

const Login: React.FC = () => {
  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    };
  });

  const handleSubmit = async (values: API.LoginForm) => {
    try {
      // 登录
      const res = await login({
        userName: values.username || '',
        passwordMd5: md5(values.password || ''),
      });
      if (res.resultCode === 200) {
        message.success('登陆成功!');
        localStorage.setItem('token', res.data as string);
        history.push('/welcome');
        return;
      }
      message.error('账号或密码错误，登录失败！');
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }
  };

  return (
    <div className={containerClassName}>
      <Helmet>
        <title>登录 - {Settings.title}</title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="登录"
          subTitle="电商系统-管理端"
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginForm);
          }}
        >
          <ProFormText
            name="username"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined />,
            }}
            placeholder="用户名"
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined />,
            }}
            placeholder="密码"
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />
          <div>默认账号：admin 密码：123456</div>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
